package com.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

public class JWTUtil {

    /**
     * 密钥
     */
    private static final String SECRET_KEY = "asdfghjklzxcvbnm";
    /**
     * 过期时间，单位毫秒
     */
    private static final long EXPIRATION_TIME = 864_000_000; // 10 days

    /**
     * 生成 token
     *
     * @param username
     * @return
     */
    public static String generateToken(String username) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + EXPIRATION_TIME);

        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(now)
                .setExpiration(expiryDate)
                .signWith(SignatureAlgorithm.HS512, SECRET_KEY)
                .compact();
    }

    /**
     * 验证 token 是否有效
     *
     * @param token
     * @return
     */
    //
    public static boolean validateToken(String token) {
        try {
            Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 从 token 中获取用户名
     */

    public static String getUsernameFromToken(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody();

        return claims.getSubject();
    }

    /**
     * 获取 token 过期时间
     *
     * @param token
     * @return
     */
    public static Date getExpirationDateFromToken(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody();
        return claims.getExpiration();
    }


    /**
     * 刷新 token
     *
     * @param token
     * @return
     */
    public static String refreshToken(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody();

        // 可以根据实际需求对 token 进行刷新，例如更新过期时间
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + EXPIRATION_TIME);
        claims.setIssuedAt(now);
        claims.setExpiration(expiryDate);

        return Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, SECRET_KEY)
                .compact();
    }

    /**
     * 验证 token 是否需要刷新
     *
     * @param token
     * @param refreshThreshold
     * @return
     */
    public static boolean isTokenNeedRefresh(String token, long refreshThreshold) {
        Date now = new Date();
        Date expiryDate = getExpirationDateFromToken(token);
        return expiryDate.getTime() - now.getTime() <= refreshThreshold;
    }


}
